package com.menghao.rpc;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>线程命名工厂.<br>
 *
 * @author MarvelCode.
 */
public class NamedThreadFactory implements ThreadFactory {

    private AtomicInteger num;
    /**
     * 线程命名前缀
     */
    private String prefix;

    /**
     * 是否为守护线程
     */
    private boolean daemon;

    private final ThreadGroup group;

    public NamedThreadFactory(String prefix, boolean daemon) {
        this.prefix = prefix + "-thread-";
        this.daemon = daemon;
        num = new AtomicInteger(1);
        SecurityManager s = System.getSecurityManager();
        this.group = s != null ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(this.group, r);
        thread.setName(prefix + num.getAndIncrement());
        thread.setDaemon(daemon);
        return thread;
    }
}
